// pages/address/add/add.js
import {
  saveAddressApi,
  getAddressDetailApi,
  updateAddressApi
} from '../../../../api/address';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    // 姓名
    name: '',
    // 电话
    phone: '',
    // 标签
    tagName: '家',
    // 用户地址
    address: '',
    // 省
    provinceCode: '',
    // 市
    cityCode: '',
    // 区
    districtCode: '',
    // 是否是默认地址
    isDefault: 0,
    // 用户选择地址 省/市/县
    region: '',
    // 地址id，用于修改地址跳转过来的地址id
    id: '',
  },
  onLoad(options) {
    this.data.id = options.id || '';
  },
  onShow() {
    if (!this.data.id) return;
    this.getAddressDetail();
  },
  async getAddressDetail() {
    const {
      name,
      phone,
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode,
      address,
      tagName,
      isDefault
    } = await getAddressDetailApi(this.data.id);

    const region = [provinceName, cityName, districtName];

    this.setData({
      name,
      phone,
      region,
      address,
      tagName,
      isDefault,
      provinceCode,
      cityCode,
      districtCode
    })
  },
  handleRegionChange(e) {
    this.setData({
      region: e.detail.value,
      provinceCode: e.detail.code[0],
      cityCode: e.detail.code[1],
      districtCode: e.detail.code[2],
    })
  },
  handleSwichChange(e) {
    this.setData({
      isDefault: +e.detail.value
    })
  },
  async saveAddress() {
    const {
      name,
      phone,
      region,
      provinceCode,
      cityCode,
      districtCode,
      address,
      tagName,
      isDefault,
      id
    } = this.data;
    if (!name) {
      wx.showToast({
        title: '请输入收货人姓名',
      })
      return;
    }
    if (!phone) {
      wx.showToast({
        title: '请输入手机号',
      })
      return;
    }
    const phoneReg = /^1[3-9][0-9]{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
      })
      return;
    }
    if (!region) {
      wx.showToast({
        title: '请选择地址',
      })
      return;
    }
    if (!address) {
      wx.showToast({
        title: '请填写详细地址',
      })
      return;
    }

    if (id) {
      // 更新
      await updateAddressApi({
        id,
        name,
        phone,
        provinceCode,
        cityCode,
        districtCode,
        address,
        tagName,
        isDefault,
      })
    } else {
      // 添加
      await saveAddressApi({
        name,
        phone,
        provinceCode,
        cityCode,
        districtCode,
        address,
        tagName,
        isDefault,
      })
    }

    const title = `${id ? '更新' : '添加'}地址成功`;
    
    wx.showToast({
      title,
      icon: 'success',
      success() {
        setTimeout(() => {
          wx.navigateBack();
        }, 500)
      },
    });
  }
})